//$URL: http://dasding.googlecode.com/svn/trunk/data/data/src/main/java/de/piratech/dasding/data/helper/PasswordHelper.java $
//$Id: PasswordHelper.java 89 2012-11-12 14:55:42Z amuthmann@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.data.helper;

import java.security.MessageDigest;
import java.util.Formatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helperclass to generate passwords
 *
 * @author deveth0
 */
public class PasswordHelper {

  private static final Logger LOG = LoggerFactory.getLogger(PasswordHelper.class);
  private static final int HASHTIMES = 1000;

  /**
   * Encrypts an password using the given salt
   *
   * @param pCleartext
   * @param pSalt
   * @return
   */
  public static String getCryptedPassword(String pCleartext, String pSalt) {
    StringBuffer stringBuffer = new StringBuffer();
    byte[] hash;
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-512");
      digest.reset();
      digest.update(pSalt.getBytes());
      hash = digest.digest(pCleartext.getBytes("UTF-8"));
      for (int i = 0; i < HASHTIMES; i++) {
        digest.reset();
        hash = digest.digest(hash);
      }
      Formatter f = new Formatter(stringBuffer);
      for (byte b : hash) {
        f.format("%02x", b);
      }
    } catch (Exception e) {
      LOG.error("", e);
    }
    String pwd = stringBuffer.toString();
    LOG.debug("encrypted pwd {}", pwd);
    return pwd;
  }
}
